package com.goldcn.common;

import com.goldcn.common.util.CommonUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.math.NumberUtils;

import java.text.NumberFormat;
import java.text.ParseException;

/**
 *
 */
public class DataUtils {

    /**
     * 判断json 是否含有有效的值
     * @param j
     * @param k
     * @return 有效则返回true
     */
    public static boolean jsonHasVal(JSONObject j, String k){
        if(j.containsKey(k)){
            if(null != j.get(k)){
                if(CommonUtils.isNotEmpty(j.getString(k))){
                    if(NumberUtils.isNumber(j.getString(k))){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 判断json 是否含有有效的值
     * @param j
     * @param k
     * @return 有效则返回true
     */
    public static String getStr(JSONObject j, String k, String d){
        if(j==null){
            return d;
        }
        if(j.containsKey(k)){
            if(null != j.get(k)){
                if(CommonUtils.isNotEmpty(j.getString(k))){
                    return j.getString(k);
                }
            }
        }
        return d;
    }

    public static String getStr(JSONObject j, String k){
        return getStr(j,k,null);
    }

    public static Number getNumber(JSONObject jsonObject, Object key) {
        if(jsonObject != null) {
            Object answer = jsonObject.get(key);
            if(answer != null) {
                if(answer instanceof Number) {
                    return (Number)answer;
                }

                if(answer instanceof String) {
                    try {
                        String e = (String)answer;
                        return NumberFormat.getInstance().parse(e);
                    } catch (ParseException var4) {
                        ;
                    }
                }
            }
        }

        return null;
    }

    public static Integer getInteger(JSONObject jsonObject, Object key) {
        Number answer = getNumber(jsonObject, key);
        return answer == null?null:(answer instanceof Integer?(Integer)answer:new Integer(answer.intValue()));
    }

    public static Integer getInteger(JSONObject jsonObject, Object key, Integer defaultValue) {
        Integer answer = getInteger(jsonObject, key);
        if(answer == null) {
            answer = defaultValue;
        }

        return answer;
    }

    /*public static void main(String[] args) {
        try {
            JSONObject jsonObject = JSONObject.fromObject("");
        } catch (Exception e) {
            System.out.printf("===");
        }

    }*/

}
